#!/usr/bin/env python  
#-*- coding:utf-8 _*-  
""" 
@author:hello_life 
@license: Apache Licence 
@file: app.py 
@time: 2022/04/17
@software: PyCharm 
description:
"""
import os

import torch
from flask import Flask,render_template,request

from models.model import TextClassification
from utils.parameters import Config
from utils.data import content_to_id

app=Flask(__name__)

#加载模型
config=Config()
model=TextClassification(config)
model_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        "save_model\\2022-04-26\\17-41-12.pt")
checkpoint=torch.load(model_path)
model.load_state_dict(checkpoint['model_state_dict'])

@app.route('/')
def home():
    return render_template("page.html")

@app.route("/predict",methods=["POST"])
def predict():
    content=[x for x in request.form.values()][0]
    tokens=torch.tensor(content_to_id(config.vocab,content)).to(torch.int32).unsqueeze(0)

    model.eval()
    with torch.no_grad():
        predict=model(tokens).argmax(1)
    return render_template("page.html",prediction_display_area="预测结果为：{}".format(predict))


if __name__=="__main__":
    app.run()